package main

import (
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"zhongxc.cc/go-common/errs"
	"zhongxc.cc/go-common/mq"
)

func main() {
	conn := mq.NewRabbitMqConnection()
	channel, err := conn.Channel()
	errs.FailOnError(err, "Failed to open a channel")
	defer func(conn *amqp.Connection) {
		_ = conn.Close()
	}(conn)
	defer func(channel *amqp.Channel) {
		_ = channel.Close()
	}(channel)

	// 创建交换机
	err = channel.ExchangeDeclare(
		"logs",   // 使用命名的交换器
		"fanout", // 交换器类型
		true,
		false,
		false,
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to declare an exchange")

	// 创建队列
	queue, err := channel.QueueDeclare(
		"",    // 空字符串作为队列名称
		false, // 非持久队列
		false, // delete when unused
		true,  // 独占队列，当前声明队列的连接关闭后即被删除
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to declare a queue")

	err = channel.QueueBind(
		queue.Name,
		"",
		"logs",
		false,
		nil,
	)

	consume, err := channel.Consume(
		queue.Name,
		"",    // exchange
		true,  // routing key
		false, // mandatory
		false, // immediate
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to register a consumer")

	forever := make(chan bool)
	go func() {
		for d := range consume {
			log.Printf(" [x] %s\n", d.Body)
		}
	}()
	log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
	<-forever
}

/**
## 列出服务器上的交换器
sudo rabbitmqctl list_exchanges
## 列出绑定关系
sudo rabbitmqctl list_bindings
*/
